package com.asiainfo.heshanghui.activity;

import android.os.Bundle;
import android.support.percent.PercentRelativeLayout;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asiainfo.heshanghui.configs.ConstantsME;
import com.asiainfo.heshanghui.configs.EventBusTag;
import com.asiainfo.heshanghui.configs.InterfaceConfig;
import com.asiainfo.heshanghui.entity.GoodsTypeInfo;
import com.asiainfo.heshanghui.entity.IdsInfo;
import com.asiainfo.heshanghui.entity.ScanInfo;
import com.asiainfo.heshanghui.networkModel.HttpUtil;
import com.framework.Utils.PreferencesHelper;
import com.framework.Utils.RegularUtil;
import com.framework.Utils.ScreenUtils;
import com.framework.Utils.ToastUtil;
import com.framework.Utils.Utils;
import com.framework.Utils.Y;
import com.framework2.base.BiuooBaseActivity;
import com.framework2.customview.TitleView;
import com.framework2.greendao.GreenDaoManager;
import com.framework2.popupwindow.SuggestPopupwindow;
import com.framework2.utils.BiuooCollectionUtil;
import com.framework2.utils.BiuooCustomProgressDialogUtils;
import com.framework2.utils.PicToastUtil;
import com.asiainfo.heshanghui.R;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 手动商品出库
 */
public class BiuooGoodsOutputManualActivity extends BiuooBaseActivity {

    @BindView(R.id.titleView)
    TitleView titleView;
    @BindView(R.id.goodsTypeLayout)
    LinearLayout goodsTypeLayout;
    @BindView(R.id.brandLayout)
    LinearLayout brandLayout;
    @BindView(R.id.typeLayout)
    LinearLayout typeLayout;
    @BindView(R.id.etImei)
    EditText etImei;
    @BindView(R.id.tvPlus)
    TextView tvPlus;
    @BindView(R.id.etCount)
    EditText etCount;
    @BindView(R.id.tvMinus)
    TextView tvMinus;
    @BindView(R.id.etPrice)
    EditText etPrice;
    @BindView(R.id.etMark)
    EditText etMark;
    @BindView(R.id.percentRoot)
    PercentRelativeLayout percentRoot;
    @BindView(R.id.tvGoodsType)
    TextView tvGoodsType;
    @BindView(R.id.tvBrand)
    TextView tvBrand;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.temp_linear)
    LinearLayout tempLinear;
    @BindView(R.id.btnContinueAdd)
    Button btnContinueAdd;
    @BindView(R.id.btnCommit)
    Button btnCommit;
    @BindView(R.id.tempBottom)
    LinearLayout tempBottom;
    @BindView(R.id.tvGoodsTypeLeft)
    TextView tvGoodsTypeLeft;
    @BindView(R.id.tvBrandLeft)
    TextView tvBrandLeft;
    @BindView(R.id.tvTypeLeft)
    TextView tvTypeLeft;
    @BindView(R.id.imeiLayout)
    LinearLayout imeiLayout;
    @BindView(R.id.tvPurchasePrice)
    TextView tvPurchasePrice;
    @BindView(R.id.purchaseLayout)
    LinearLayout purchaseLayout;
    @BindView(R.id.ivGoodsTpe)
    ImageView ivGoodsTpe;
    @BindView(R.id.ivBrand)
    ImageView ivBrand;
    @BindView(R.id.ivType)
    ImageView ivType;


    private GoodsTypeInfo goodsType = new GoodsTypeInfo();
    private GoodsTypeInfo brand = new GoodsTypeInfo();
    private GoodsTypeInfo type = new GoodsTypeInfo();
    private ScanInfo scanInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setTranslucentStatus(this, true);
        Utils.setStatusBarTintDrawable(this, R.mipmap.biuoo_bg_top);
        setContentView(R.layout.biuoo_activity_goods_output_manual);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    //eventBus通知新消息
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.GOODS_TYPE)
    public void receivedGOODS_TYPE(GoodsTypeInfo info) {
        //商品类型
        goodsType = info;
        tvGoodsType.setText(info.getTitle());
        etImei.setVisibility(TextUtils.equals(goodsType.getTitle(), "手机") ? View.VISIBLE : View.GONE);
    }

    //eventBus通知新消息
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.BRAND)
    public void receivedBrand(GoodsTypeInfo info) {
        //品牌
        brand = info;
        tvBrand.setText(info.getTitle());
    }

    //eventBus通知新消息
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.TYPE)
    public void receivedType(GoodsTypeInfo info) {
        //类型
        type = info;
        tvType.setText(info.getTitle());
    }

//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.tv_next:
//                Utils.isCloseSoftInputMethod(this, et_input_phone, true);
//                if (null == et_input_phone.getText() || TextUtils.isEmpty(et_input_phone.getText()) || !Utils.isMobileNO(et_input_phone.getText().toString())) {
//                    ToastUtil.getInstance().showToast("请输入正确手机号码");
//                    et_input_phone.requestFocus();
//                } else {
//                    BiuooCustomProgressDialogUtils.showProcessDialog(this, "检查手机号");
//                    String[] array = getResources().getStringArray(R.array.biuoo_phone);
//                    boolean contains = false;
//                    for (int i = 0; i < array.length; i++) {
//                        if (TextUtils.equals(et_input_phone.getText(), array[i])) {
//                            contains = true;
//                        }
//                    }
//                    PreferencesHelper.getInstance().putInfo("phone",et_input_phone.getText().toString());
//                    if (contains) {
//                        Utils.h.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                BiuooCustomProgressDialogUtils.dismissProcessDialog();
//                                PreferencesHelper.getInstance().putInfo("Position","");
//                                startActivity(BiuooGuideActivity.class);
//                            }
//                        }, 2000);
//                    } else {
//                        Utils.h.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                BiuooCustomProgressDialogUtils.dismissProcessDialog();
//                                ToastUtil.getInstance().showToast("用户手机号不合法，请重新输入");
//                            }
//                        }, 2000);
//
//                    }
//                }
////                startActivity(MessageCenterActivity.class);
//                break;
//            default:
//                break;
//        }
//    }


    private void initView() {
        titleView.setTitle("商品出库");
        int height = ScreenUtils.getInstance().getScreenHeightPx(this) - ScreenUtils.getInstance().getStatusBarHeightPx(this) - ScreenUtils.getInstance().dip2px(this, 50);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
        percentRoot.setLayoutParams(layoutParams);
    }

    private void initEvent() {
        etImei.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (RegularUtil.getInstance().isNumberAtLeast15bit(s.toString())) {
                    BiuooCustomProgressDialogUtils.showProcessDialog(BiuooGoodsOutputManualActivity.this, "检查库存");
                    onClickCheckImei(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = etPrice.getText().toString();
                etPrice.setText(temp.substring(0, temp.length() - 1));
                etPrice.setSelection(etPrice.getText().toString().length());
            }
        });
    }

    /**
     * 点击检查ime
     *
     * @param info
     */
    private void onClickCheckImei(String info) {
        if (RegularUtil.getInstance().isNumberAtLeast15bit(info.trim())) {
            BiuooCustomProgressDialogUtils.showProcessDialog(this, "正在查询IMEI");
            Utils.isCloseSoftInputMethod(this, etImei, true);
            if (TextUtils.isEmpty(PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId))) {
                requestJustShopIds(info);
            } else {
                requestQueryQRcode(info, PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId));
            }
        } else {
            PicToastUtil.showPicToast(this, "IMEI必须为15位数字");
        }
    }

    private void showSuggestPopupWindow() {
        final SuggestPopupwindow pop = new SuggestPopupwindow(this);
        pop.setSureButtonText("重新输入");
        pop.setOnSureClickListener(new SuggestPopupwindow.OnSureClickListener() {
            @Override
            public void onSureClickListener(String info) {
                pop.dismiss();
                etImei.setText("");
            }
        });
        pop.setOnCancelClickListener(new SuggestPopupwindow.OnCancelClickListener() {
            @Override
            public void onCancelClickListener() {
                pop.dismiss();
                etImei.setText("");
            }
        });
        try {
            pop.showAsDropDown(titleView.getRightLayout());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求查询二维码code
     */
    private void requestQueryQRcode(String code, String shopId) {
        if (TextUtils.isEmpty(code))
            return;
        HttpUtil.getInstance().requestQueryQRcode(this, InterfaceConfig.queryCode, shopId, code, new HttpUtil.OnRequestResult<ScanInfo>() {
            @Override
            public void onSuccess(ScanInfo... scanInfo) {
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                if (null != scanInfo) {
                    BiuooGoodsOutputManualActivity.this.scanInfo = scanInfo[0];
                    scanInfo[0].setCount(1);
                    tvGoodsTypeLeft.setText("商品类型");
                    tvBrandLeft.setText("品牌");
                    tvTypeLeft.setText("类型");
                    tvGoodsType.setText("手机");
                    tvBrand.setText(scanInfo[0].getContent());
                    tvType.setText(scanInfo[0].getContent());
                    etImei.setBackgroundResource(R.drawable.shape_gray_white_stroke_10px);
                    ivGoodsTpe.setVisibility(View.INVISIBLE);
                    ivBrand.setVisibility(View.INVISIBLE);
                    ivType.setVisibility(View.INVISIBLE);
                    etImei.setEnabled(false);
                    tvGoodsType.setEnabled(false);
                    tvBrand.setEnabled(false);
                    tvType.setEnabled(false);
                    purchaseLayout.setVisibility(View.VISIBLE);
                    tvPurchasePrice.setText(scanInfo[0].getPurchasePrice());
                    tvPurchasePrice.setBackgroundResource(R.drawable.shape_gray_white_stroke_10px);
                } else {
                    showSuggestPopupWindow();
                }
            }

            @Override
            public void onFail(int code, String msg) {
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
                if (code == 1) {
                    showSuggestPopupWindow();
                } else {
                    ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "查询IMEI失败" : msg);
                }
            }
        });
    }

    private void requestJustShopIds(final String code) {
        HttpUtil.getInstance().requestJustShopIds(this, InterfaceConfig.shopIds, new HttpUtil.OnRequestListResult<IdsInfo>() {
            @Override
            public void onSuccess(List<IdsInfo> list, String... msg) {
                if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
                    PreferencesHelper.getInstance().putInfo(ConstantsME.currentShopId, list.get(0).getShopId());
                    PreferencesHelper.getInstance().putInfo(ConstantsME.companyId, list.get(0).getCompanyId());
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < list.size(); i++) {
                        if (i == 0) {
                            stringBuilder.append(list.get(i).getShopId());
                        } else {
                            stringBuilder.append(",").append(list.get(i).getShopId());
                        }
                    }
                    PreferencesHelper.getInstance().putInfo(ConstantsME.shopIds, stringBuilder.toString());
                    requestQueryQRcode(code, list.get(0).getShopId());
                }
            }

            @Override
            public void onFail(int code, String msg) {
                ToastUtil.getInstance().showToast(TextUtils.isEmpty(msg) ? "未获取店铺Id" : msg);
                BiuooCustomProgressDialogUtils.dismissProcessDialog();
            }
        });
    }


    /**
     * @param scanInfo scanInfo
     */
    @SuppressWarnings("unchecked")
    private void insertOrUpdateDB(final ScanInfo scanInfo) {
        if (null == scanInfo)
            return;
        List list = GreenDaoManager.getInstance().queryEntityList(this, ScanInfo.class);
        if (BiuooCollectionUtil.getInstance().isEmpty(list)) {
            boolean a = GreenDaoManager.getInstance().insertEntity(this, scanInfo);
            Y.y("插入数据库:" + a);
        } else {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                ScanInfo info = (ScanInfo) list.get(i);
                if (null != info && TextUtils.equals(info.getImei(), scanInfo.getImei())) {
                    info.setPrice(scanInfo.getPrice());
                    GreenDaoManager.getInstance().updateEntity(this, info);
                    return;
                }
            }
        }
    }

    @OnClick({R.id.goodsTypeLayout, R.id.brandLayout, R.id.typeLayout, R.id.tvPlus, R.id.tvMinus, R.id.btnContinueAdd, R.id.btnCommit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.goodsTypeLayout:
                PicToastUtil.showPicToast(this, "商品类型");
                Bundle bundle = new Bundle();
                bundle.putString(ConstantsME.title, "商品类型");
                bundle.putInt(ConstantsME.position, 0);
                bundle.putString(ConstantsME._interface, InterfaceConfig.goodsType);
                bundle.putString(ConstantsME.classId, goodsType.getId());
                bundle.putString(ConstantsME.brandId, brand.getId());
                bundle.putString(ConstantsME.modelId, type.getId());
                startActivity(BiuooGoodsTypeActivity.class, bundle);
                break;
            case R.id.brandLayout:
                PicToastUtil.showPicToast(this, "品牌");
                if (goodsType == null) {
                    PicToastUtil.showPicToast(BiuooGoodsOutputManualActivity.this, "请先选择商品类型!");
                    return;
                }
                Bundle bundle1 = new Bundle();
                bundle1.putString(ConstantsME.title, "品牌");
                bundle1.putInt(ConstantsME.position, 1);
                bundle1.putString(ConstantsME._interface, InterfaceConfig.brand);
                bundle1.putString(ConstantsME.classId, goodsType.getId());
                bundle1.putString(ConstantsME.brandId, brand.getId());
                bundle1.putString(ConstantsME.modelId, type.getId());
                startActivity(BiuooGoodsTypeActivity.class, bundle1);
                break;
            case R.id.typeLayout:
                if (brand == null) {
                    PicToastUtil.showPicToast(BiuooGoodsOutputManualActivity.this, "请先选择品牌!");
                    return;
                }
                Bundle bundle2 = new Bundle();
                bundle2.putString(ConstantsME.title, "型号");
                bundle2.putInt(ConstantsME.position, 2);
                bundle2.putString(ConstantsME._interface, InterfaceConfig.type);
                bundle2.putString(ConstantsME.classId, goodsType.getId());
                bundle2.putString(ConstantsME.brandId, brand.getId());
                bundle2.putString(ConstantsME.modelId, type.getId());
                startActivity(BiuooGoodsTypeActivity.class, bundle2);
                break;
            case R.id.tvPlus:
                PicToastUtil.showPicToast(this, "+");
                break;
            case R.id.tvMinus:
                PicToastUtil.showPicToast(this, "-");
                break;
            case R.id.btnContinueAdd:
                PicToastUtil.showPicToast(this, "继续添加");
                if (isLegal()) {
                    finish();
                }
                break;
            case R.id.btnCommit:
                PicToastUtil.showPicToast(this, "提交出库");
                if (isLegal()) {

                }
                break;
        }
    }

    private boolean isLegal() {
        if (null == scanInfo) {
            PicToastUtil.showPicToast(BiuooGoodsOutputManualActivity.this, "请选择相关数据!");
            return false;
        }
        if (TextUtils.isEmpty(goodsType.getId())) {
            PicToastUtil.showPicToast(BiuooGoodsOutputManualActivity.this, "请先选择商品类型!");
            return false;
        } else if (TextUtils.isEmpty(brand.getId())) {
            PicToastUtil.showPicToast(BiuooGoodsOutputManualActivity.this, "请先选择品牌!");
            return false;
        } else if (TextUtils.isEmpty(type.getId())) {
            PicToastUtil.showPicToast(BiuooGoodsOutputManualActivity.this, "请先选择类型!");
            return false;
        } else if (TextUtils.equals("手机", goodsType.getTitle())) {
            PicToastUtil.showPicToast(BiuooGoodsOutputManualActivity.this, "请输入IMEI");
            return false;
        } else if (TextUtils.isEmpty(etPrice.getText())) {
            PicToastUtil.showPicToast(BiuooGoodsOutputManualActivity.this, "请输入价格!");
            return false;
        }
        if (null != scanInfo) {
            insertOrUpdateDB(scanInfo);
        }
        return true;
    }
}
